package com.molyfun.parents.activity.course;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseChoosePicActivity;
import com.molyfun.parents.activity.common.attachment.AttachmentView;
import com.molyfun.parents.dao.entity.CourseFeedBackDB;
import com.molyfun.parents.dao.gen.CourseFeedBackDBDao;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.impl.IPicUploadCallback;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.AddCourseFeedBackRequest;
import com.molyfun.parents.rest.bean.CourseFeedbackEditRequest;
import com.molyfun.parents.rest.bean.CourseFeedbackListResponse;
import com.molyfun.parents.rest.bean.MediaobjectlistBean;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.UIUtils;
import com.molyfun.parents.view.common.MfEditText;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 课程反馈编辑添加页面
 */
public class CourseFeedbackEditActivity extends BaseChoosePicActivity implements View.OnClickListener, IPicUploadCallback, AttachmentView.AttachmentAddCallback{

    @InjectView(R.id.course_feedback_text)
    MfEditText mFeedbackEdt;
    @InjectView(R.id.course_feedback_attachview)
    AttachmentView mAttachmentView;
    @InjectView(R.id.commit)
    TextView mCommit;
    @InjectView(R.id.base_title)
    TextView mTitle;
    @InjectView(R.id.base_title_left)
    ImageView mTitleBack;

    private String mCourseId, mCourseDownloadKey;
    private CourseFeedBackDBDao courseFeedBackDBDao;
    private CourseFeedbackListResponse.CourseFeedbackBean courseFeedbackBean;

    public static void startActivity(Context context, String courseId, String courseDownloadKey, CourseFeedbackListResponse.CourseFeedbackBean courseFeedbackBean) {
        Intent intent = new Intent();
        intent.putExtra(Const.COURSE_ID, courseId);
        intent.putExtra(Const.COURSE_DOWNLOAD_ID, courseDownloadKey);
        intent.putExtra(Const.COURSE_FEEDBACK_BEAN, courseFeedbackBean);
        intent.setClass(context, CourseFeedbackEditActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_feedback);
        ButterKnife.inject(this);

        mTitleBack.setOnClickListener(this);

        getSupportActionBar().setTitle("");


        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        courseFeedBackDBDao = daoSession.getCourseFeedBackDBDao();
        mCourseId = getIntent().getStringExtra(Const.COURSE_ID);
        courseFeedbackBean = getIntent().getParcelableExtra(Const.COURSE_FEEDBACK_BEAN);
        mCourseDownloadKey = getIntent().getStringExtra(Const.COURSE_DOWNLOAD_ID);

        mFeedbackEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    mCommit.setEnabled(true);
                }else{
                    mCommit.setEnabled(false);
                }
            }
        });

        CourseFeedBackDB courseFeedBackDB = courseFeedBackDBDao.queryBuilder().where(CourseFeedBackDBDao.Properties.DownloadKeyId.eq(mCourseDownloadKey)).build().unique();
        if (courseFeedBackDB != null) {
            mFeedbackEdt.setText(courseFeedBackDB.getFeedback());
        }
        if (courseFeedbackBean != null) {
            mFeedbackEdt.setText(courseFeedbackBean.getContent());
            mAttachmentView.addList(courseFeedbackBean.getMediaobjectlist());
            mTitle.setText("修改反馈");
        }else{
            mTitle.setText("添加反馈");
        }

        mCommit.setOnClickListener(this);
        mAttachmentView.setAttachmentAddCallback(this);
    }

    @Override
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
        MediaobjectlistBean mediaAttachment = new MediaobjectlistBean();
        mediaAttachment.setUrl(originalUrl);
        mediaAttachment.setType(1);
        mAttachmentView.addAttachment(mediaAttachment);
    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {
    }

    public void onPictureUploadBegin(String path, String UploadPath) {

    }

    @Override
    public void onVideoUploadSuccess(String cover, String path) {
        System.out.println("cover--->" + cover);
        System.out.println("path--->" + path);

        MediaobjectlistBean mediaAttachment = new MediaobjectlistBean();
        mediaAttachment.setUrl(path);
        mediaAttachment.setType(2);
        mAttachmentView.addAttachment(mediaAttachment);
    }

    @Override
    public void onAttachmentAdd() {
        chooseMedia();
    }

    @Override
    public String getAttachmentFolder() {
        return "coursefb";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.base_title_left:
                if (!TextUtils.isEmpty(mFeedbackEdt.getText().toString().trim())) {
                    CourseFeedBackDB courseFeedBackDB = courseFeedBackDBDao.queryBuilder().where(CourseFeedBackDBDao.Properties.DownloadKeyId.eq(mCourseDownloadKey)).build().unique();
                    if (courseFeedBackDB != null) {
                        courseFeedBackDB.setFeedback(mFeedbackEdt.getText().toString().trim());
                        courseFeedBackDBDao.update(courseFeedBackDB);
                    } else {
                        CourseFeedBackDB newCourseFeedBackDB = new CourseFeedBackDB();
                        newCourseFeedBackDB.setFeedback(mFeedbackEdt.getText().toString().trim());
                        newCourseFeedBackDB.setDownloadKeyId(mCourseDownloadKey);
                        courseFeedBackDBDao.insert(newCourseFeedBackDB);
                    }
                }
                finish();
                break;
            case R.id.commit:
                if (TextUtils.isEmpty(mFeedbackEdt.getText().toString().trim())) {
                    UIUtils.showToast(CourseFeedbackEditActivity.this, "请输入反馈内容");
                    return;
                }
                mCommit.setEnabled(false);
                sendFeedBack();
                break;
        }
    }

    private void sendFeedBack() {
        if (courseFeedbackBean != null) {
            final CourseFeedbackEditRequest courseFeedbackEditRequest = new CourseFeedbackEditRequest();
            courseFeedbackEditRequest.setContent(mFeedbackEdt.getText().toString().trim());
            courseFeedbackEditRequest.setId(courseFeedbackBean.getId());
            courseFeedbackEditRequest.setMediaobjectlist(mAttachmentView.getAttachment());
            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().updateCourseFeedback(courseFeedbackEditRequest);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if (response.body().getCode() == 200) {
//                        if (mCourseFeedbackCallback != null) {
//                            mCourseFeedbackCallback.onFeedbackUpdateSuccess(courseFeedbackEditRequest);
//                        }
                        //TODO 删除数据库操作

                        UIUtils.showToast(CourseFeedbackEditActivity.this, "提交成功");
                        finish();


                    } else {
                        UIUtils.showToast(CourseFeedbackEditActivity.this, response.body().getMsg());
                        mCommit.setEnabled(true);
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                    mCommit.setEnabled(true);
                }
            });
        } else {
            AddCourseFeedBackRequest addCourseFeedBackRequest = new AddCourseFeedBackRequest();
            addCourseFeedBackRequest.setContent(mFeedbackEdt.getText().toString().trim());
            addCourseFeedBackRequest.setCoursesummaryid(mCourseId);
            addCourseFeedBackRequest.setMediaobjectlist(mAttachmentView.getAttachment());


            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().addCourseFeedBack(addCourseFeedBackRequest);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                    if (response.body().getCode() == 200) {

                            Message message = new Message();
                            message.what = EventDispatcherEnum.UI_EVENT_COURSE_FREEBACK_UPDATE;
                            MFPApplication.getInstance().getEventDispatcher().sendMessage(message);


                        CourseFeedBackDB courseFeedBackDB = courseFeedBackDBDao.queryBuilder().where(CourseFeedBackDBDao.Properties.DownloadKeyId.eq(mCourseDownloadKey)).build().unique();
                        if (courseFeedBackDB != null) {
                            courseFeedBackDBDao.delete(courseFeedBackDB);
                        }

                        UIUtils.showToast(CourseFeedbackEditActivity.this, "提交成功");
                        finish();

                    } else {
                        UIUtils.showToast(CourseFeedbackEditActivity.this, response.body().getMsg());
                        mCommit.setEnabled(true);
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {
                    mCommit.setEnabled(true);
                }
            });
        }


    }

}
